package lock.demo;

import center.ZkConfig;
import common.ZkUtil;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2020-07-16
 * Time: 14:28
 *
 * @author zyh
 */
public class LockTest {

    ZooKeeper zooKeeper;

    @Before
    public void init() throws IOException, InterruptedException {
        ZkConfig zkConfig = new ZkConfig();

        zkConfig.setConnectString("192.168.1.38:2181,192.168.1.39:2181,192.168.1.40:2181,192.168.1.41:2181");
        zkConfig.setSessionOutTime(4000);

        ZkUtil zkUtil = new ZkUtil(zkConfig);

        this.zooKeeper = zkUtil.getZookeeper();
    }

    @Test
    public void testLock() throws KeeperException, InterruptedException {
        System.out.println("test lock");
        for (int i = 0; i <10 ; i++) {
            new Thread(() -> {
                String threadName = Thread.currentThread().getName();

                ZkLock zkLock = new ZkLock(zooKeeper, threadName);
                System.out.println(threadName + "lock");
                try {
                    System.out.println(threadName + "lock");
                    zkLock.trylock();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(threadName + "---working----");
                zkLock.unlock();
            }).start();

        }
        while (true){}

    }

}
